<script setup lang="ts" name="permission">
import { ref, watch, onMounted } from "vue"
import { Search, Refresh } from "@element-plus/icons-vue"
import UserDia from "./components/userDia.vue"
import { listMenu, getMenu, delMenu } from '@/common/apis/system/menu'
import { ElMessageBox, ElMessage } from 'element-plus'
import { handleTree } from '@/common/utils/ruoyi'
import { useAutoRefresh } from "@/layouts/composables/useAutoRefresh"
const searchData = ref({
  menuName: '',
  menuType: '',
  create_time: [],
  status: '',
})
defineOptions({
  // 命名当前组件
  name: "SystemMenu"
})
function handleSearchMore() {
  searchMore.value = !searchMore.value
  if (!searchMore.value) {
    resetSearch()
  }
}
const tableData = ref<any[]>([])
// 加载中
const loading = ref(false)
// 搜索表单
const searchFormRef = ref()
// 弹窗
const dialogShow = ref(false)
// 菜单禁用
const menuDisabled = ref(false)
// 顶级菜单
const topMenu = ref('')
// 搜索更多
const searchMore = ref(false)
// 搜索内容
const searchKey = ref('')
// 搜索
const search = () => {
  if (searchKey.value || searchData.value.menuName || searchData.value.menuType || searchData.value.status || searchData.value.create_time.length > 0) {
    getTableDataSearch()
  } else {
    getTableData()
  }
}
// 重置
const resetSearch = () => {
  searchData.value = {
    menuName: '',
    menuType: '',
    status: '',
    create_time: [],
  }
  getTableDataSearch()
}
// 菜单id
const menuId = ref('')
// 新增菜单
const handleCreateTask = () => {
  dialogShow.value = true
  menuDisabled.value = false
  menuId.value = ''
  topMenu.value = '主菜单'
}
const topRoot = (data: any, id: any) => {
  if (data.parentId !== 0) {
    data.rootId = id
  }
  if (data.children) {
    data.children.forEach((item: any) => {
      item.rootId = id
      if (item.children) {
        item.children.forEach((it: any) => {
          topRoot(it, id)
        })
      }
    })
  }
}
// 获取表格数据
const getTableData = () => {
  listMenu({}).then((res: any) => {
    tableData.value = handleTree(res.data, 'menuId', 'parentId', 'children')
    tableData.value.forEach((item: any) => {
      item.rootId = item.menuId
      topRoot(item, item.menuId)
    })
  })
}
// 将tableData的每一项包括children都要去进行比较，如果有值就把最上级的数据push到data中
const sreachFun = (data: any, list: any[]) => {
  // 2022-02-02 09:02:02 转成毫秒
  const createTime = new Date(searchData.value.create_time[0]).getTime()
  const endTime = new Date(searchData.value.create_time[1]).getTime()
  data.forEach((item: any) => {
    item.searchKey = item.menuName
    if (searchKey.value && item.menuName.includes(searchKey.value) || searchData.value.menuName && item.searchKey.includes(searchData.value.menuName) || item.menuType === searchData.value.menuType || item.status === searchData.value.status) {
      if (searchData.value.create_time.length > 0) {
        if (new Date(item.createTime).getTime() >= createTime && new Date(item.createTime).getTime() <= endTime) {
          tableData.value.forEach((it: any) => {
            if (it.menuId === item.rootId) {
              list.push(it)
            }
          })
        }
      } else {
        tableData.value.forEach((it: any) => {
          if (it.menuId === item.rootId) {
            if (list.length > 0) {
              const isExist = list.some((itx: any) => itx.menuId === it.menuId)
              if (!isExist) {
                list.push(it)
              }
            } else {
              list.push(it)
            }
          }
        })
      }
    }
    if (item.children) {
      sreachFun(item.children, list)
    }
  })
}
// 检索
const getTableDataSearch = () => {
  const params = {
    menuName: searchData.value.menuName || '',
    menuType: searchData.value.menuType || '',
    status: searchData.value.status || '',
    searchKey: searchKey.value || '',
  }
  const data: any[] = []
  // searchKey和params里面有值，就进行检索
  if (searchKey.value || params.menuName || params.menuType || params.status || searchData.value.create_time.length > 0) {
    sreachFun(tableData.value, data)
    tableData.value = data
  } else {
    tableData.value = tableData.value
  }
}
onMounted(() => {
  getTableData()
})
// 获取行键
const getRowKeys = (row: any) => {
  return row.menuId
}
// 查看
const handleDetail = (id: any) => {
  menuId.value = id + ''
  dialogShow.value = true
  getMenu(id).then((res: any) => {
  })
}
// 删除
const handleDelete = (id: any, name: any) => {
  ElMessageBox.confirm(`确定要删除${name}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delMenu(id).then((res: any) => {
      ElMessage.success('删除成功')
      getTableData()
    })
  })
}
const topType = ref('M')
// 弹窗
const dialogShowChange = (val: boolean) => {
  dialogShow.value = val
  menuId.value = ''
  topMenu.value = ''
  menuDisabled.value = false
  topType.value = 'M'
  getTableData()
}
// 新增子级
const handleAdd = (row: any) => {
  menuDisabled.value = true
  topMenu.value = row.menuId
  topType.value = row.menuType
  dialogShow.value = true
}
useAutoRefresh(getTableData)
</script>

<template>
  <div class="app-container pager-container">
    <div class="cc-search">
      <div class="cc-search-common">
        <el-input v-model="searchKey" size="large" placeholder="请输入搜索内容" class="csc-search-input"
          @keydown.enter="search">
          <template #append>
            <el-button :icon="Search" v-throttle="() => search()" />
          </template>
        </el-input>
        <div class="csc-more" @click="handleSearchMore">
          <span>更多</span>
          <el-icon v-if="!searchMore">
            <ArrowDown />
          </el-icon>
          <el-icon v-else>
            <ArrowUp />
          </el-icon>
        </div>
      </div>
      <div class="cc-search-common-more" v-if="searchMore">
        <el-form ref="searchFormRef" :model="searchData" :inline="true">
          <el-form-item prop="menuName" label="菜单名称">
            <el-input v-model="searchData.menuName" @change="search()" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="menuType" label="菜单类型">
            <el-select v-model="searchData.menuType" clearable @change="search()" style="width: 240px"
              placeholder="请选择">
              <el-option label="目录" value="M" />
              <el-option label="菜单" value="C" />
              <el-option label="按钮" value="F" />
            </el-select>
          </el-form-item>
          <el-form-item prop="status" label="菜单状态">
            <el-select v-model="searchData.status" clearable @change="search()" style="width: 240px" placeholder="请选择">
              <el-option label="正常" value="1" />
              <el-option label="停用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="time_range" label="时间范围">
            <el-date-picker v-model="searchData.create_time" type="daterange" unlink-panels range-separator="至"
              value-format="YYYY-MM-DD" start-placeholder="开始时间" end-placeholder="结束时间" @change="search()" />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-loading="loading" class="content-other">
      <div class="flex-between mb-main-padding">
        <div class="flex-y-center tag">
          <el-button type="primary" @click="handleCreateTask">新增</el-button>
        </div>
      </div>
      <div class="cpi-content-main">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table ref="tableRef" v-loading="loading" :height="height" :width="width" :data="tableData"
              :default-expand-all="false" :row-key="getRowKeys" show-overflow-tooltip
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
              <el-table-column prop="menuName" label="菜单名称" header-align="left" />
              <el-table-column prop="path" label="菜单地址" header-align="left" />
              <el-table-column prop="menuType" label="类型" header-align="left">
                <template #default="scope">
                  <div class="green" v-if="scope.row.menuType === 'M'">目录</div>
                  <div class="red" v-else-if="scope.row.menuType === 'C'">菜单</div>
                  <div class="red" v-else>按钮</div>
                </template>
              </el-table-column>
              <el-table-column prop="visible" label="可见" header-align="left">
                <template #default="scope">
                  <div class="green" v-if="scope.row.visible === 0">显示</div>
                  <div class="red" v-else>隐藏</div>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" header-align="left">
                <template #default="scope">
                  <div class="green" v-if="scope.row.status === 0">正常</div>
                  <div class="red" v-else>停用</div>
                </template>
              </el-table-column>
              <el-table-column prop="perms" label="权限标识 " header-align="left" />
              <el-table-column prop="createTime" label="创建时间" header-align="left" width="180" />
              <el-table-column fixed="right" label="操作" align="center" width="140">
                <template #default="scope">
                  <el-space :size="12">
                    <el-link :underline="false" @click.stop="handleDetail(scope.row.menuId)" title="查看">
                      <el-icon :size="18" color="#409EFF">
                        <View />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" v-if="scope.row.menuType !== 'F'" @click.stop="handleAdd(scope.row)"
                      title="新增子级">
                      <el-icon :size="18" color="green">
                        <Plus />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" type="danger"
                      @click.stop="handleDelete(scope.row.menuId, scope.row.menuName)" title="删除">
                      <el-icon :size="18">
                        <Delete />
                      </el-icon>
                    </el-link>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-auto-resizer>
      </div>
    </div>
    <UserDia :dialogShow="dialogShow" :topType="topType" :menuDisabled="menuDisabled" :topMenu="topMenu"
      @update:dialogShow="dialogShowChange" :menuId="menuId" />
  </div>
</template>
<style lang="scss" scoped>
.csc-search-common-left {
  display: flex;
}

.csc-base-data {
  float: right;
}

.red {
  display: inline-block;
  width: 46px;
  height: 26px;
  color: #815219;
  border: 1px solid #815219;
  border-radius: 4px;
  text-align: center;
  line-height: 26px;
}

.green {
  display: inline-block;
  width: 46px;
  height: 26px;
  color: green;
  border: 1px solid green;
  border-radius: 4px;
  text-align: center;
  line-height: 26px;
}
</style>
